package com.studyroom.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.studyroom.entity.Notice;
import com.studyroom.mapper.NoticeMapper;
import com.studyroom.service.NoticeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;

@Service
public class NoticeServiceImpl extends ServiceImpl<NoticeMapper, Notice> implements NoticeService {

    private static final Logger log = LoggerFactory.getLogger(NoticeServiceImpl.class);

    @Override
    public IPage<Notice> getNotices(Integer current, Integer size, String title, Integer status) {
        LambdaQueryWrapper<Notice> wrapper = new LambdaQueryWrapper<>();
        
        // 添加标题查询条件
        if (StringUtils.hasText(title)) {
            wrapper.like(Notice::getTitle, title);
        }
        
        // 添加状态查询条件
        if (status != null) {
            wrapper.eq(Notice::getStatus, status);
        }
        
        // 按创建时间倒序排序
        wrapper.orderByDesc(Notice::getCreatedAt);
        
        IPage<Notice> page = page(new Page<>(current, size), wrapper);
        
        // 添加调试日志
        if (page.getRecords().size() > 0) {
            Notice firstNotice = page.getRecords().get(0);
            log.debug("Notice data from service:");
            log.debug("- ID: {}", firstNotice.getId());
            log.debug("- Title: {}", firstNotice.getTitle());
            log.debug("- CreatedAt: {}", firstNotice.getCreatedAt());
            log.debug("- CreatedAt class: {}", firstNotice.getCreatedAt().getClass().getName());
        }
        
        return page;
    }

    @Override
    public Notice getNoticeById(Long id) {
        return getById(id);
    }

    @Override
    public boolean createNotice(Notice notice) {
        notice.setCreatedAt(LocalDateTime.now());
        notice.setUpdatedAt(LocalDateTime.now());
        notice.setStatus(0); // 默认未发布
        return save(notice);
    }

    @Override
    public boolean updateNotice(Notice notice) {
        notice.setUpdatedAt(LocalDateTime.now());
        return updateById(notice);
    }

    @Override
    public boolean deleteNotice(Long id) {
        return removeById(id);
    }

    @Override
    public boolean publishNotice(Long id) {
        Notice notice = getById(id);
        if (notice != null) {
            notice.setStatus(1);
            notice.setUpdatedAt(LocalDateTime.now());
            return updateById(notice);
        }
        return false;
    }
} 